import { defineStore } from "pinia";
import { store } from "@/store";
import { userType } from "./types";
import { routerArrays } from "@/layout/types";
import { router, resetRouter } from "@/router";
import { storageSession, storageLocal } from "@pureadmin/utils";
import { getLogin } from "@/api/user";
import { UserResult, RefreshTokenResult } from "@/api/user";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { setToken, removeToken, getUserinfo } from "@/utils/auth";
import { http } from "@/utils/http";
import { message } from "@/utils/message";

export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    // 用户名
    username: getUserinfo()?.username ?? "",
    // 页面级别权限
    roles: getUserinfo()?.roles ?? [],
    accountConfig: [],
    accountInfo: {
      stateConfig: {}
    },
    permissions: [],
    avatar: "",
    userId: "",
    connectIntranet: false
  }),
  actions: {
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise<UserResult>((resolve, reject) => {
        getLogin(data)
          .then(data => {
            if (data) {
              setToken(data.data as any);
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.roles = [];
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      // const { DEV } = import.meta.env;
      // if (DEV) {
        router.push("/login");
      // } else {
      //   location.href = location.origin + "/#/login";
      // }
    },
    async tryConnectIntranet(e) {
      if (!e) {
        return Promise.resolve();
      }
      try {
        const res = await http.request("get", e, {
          timeout: 2000,
          headers: {
            "Access-Control-Allow-Private-Network": true
          }
        });
        localStorage.setItem("isInner", 1 as any);
        this.connectIntranet = true;
        localStorage.getItem("material_token") && this.getInfo();
        // return Promise.resolve();
      } catch (e) {
        localStorage.setItem("isInner", 0 as any);
        this.connectIntranet = false;
        // return Promise.resolve();
      }

      setTimeout(function () {
        message(
          "检测到当前网络环境：".concat(
            this.connectIntranet ? "内网" : "外网",
            "访问"
          ),
          {
            showClose: true,
            type: "success",
            duration: 2500
          }
        );
      }, 1000);
    },
    async getInfo() {
      const useinfo = getUserinfo();
      // const res = await getLoginInfoApi();
      const res = {
        data: {
          ...useinfo,
          permissions: [],
          stateConfig: {
            isOpenVideoState: 1,
            isShowStateComment: 1,
            isShowStateMaterial: 1,
            isShowStateOther: 1,
            isShowStateVideo: 1,
            videoStateValue: 1
          }
        }
      };
      if (!res.data) {
        return Promise.reject("Verification failed, please Login again.");
      }
      this.accountInfo = res.data;
      this.permissions = [-1].concat([...res.data.permissions]) || [-1];
      const { username, pic, id, innerNetCheckAddress } = res.data as any;
      this.username = username;
      this.avatar = pic;
      this.userId = id;
      if (localStorage.getItem("isInner")) {
        const atryConnectIntranetRes = await this.tryConnectIntranet(
          innerNetCheckAddress
        );
      } else {
        this.connectIntranet = JSON.parse(localStorage.getItem("isInner"));
      }
      return Promise.resolve(res.data);
    },
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}

export function hasPerm(authPermission) {
  return true;
  // if (useUserStoreHook().accountInfo.accountType) {
  //   return true;
  // }
  // if (
  //   authPermission &&
  //   authPermission instanceof Array &&
  //   authPermission.length > 0
  // ) {
  //   return useUserStoreHook().permissions.some(permission => {
  //     return authPermission.includes(permission);
  //   });
  // }
  // return false;
}
